from .. import db
from datetime import datetime
from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash

class User(UserMixin):
    def __init__(self, id, username, email, password_hash, role='viewer', is_active=True):
        self.id = id
        self.username = username
        self.email = email
        self.password_hash = password_hash
        self.role = role
        self._is_active = is_active
        self.created_at = datetime.utcnow()
    
    @property
    def is_active(self):
        return self._is_active
    
    @is_active.setter
    def is_active(self, value):
        self._is_active = bool(value)
    
    def set_password(self, password):
        self.password_hash = generate_password_hash(password)
    
    def check_password(self, password):
        return check_password_hash(self.password_hash, password)
    
    @staticmethod
    def create_user(username, email, password, role='viewer', is_active=True):
        """创建新用户"""
        user_id = len(db.users) + 1
        user = User(
            id=user_id,
            username=username,
            email=email,
            password_hash='',
            role=role,
            is_active=is_active
        )
        user.set_password(password)
        
        db.users.append(user)
        return user
    
    @staticmethod
    def find_by_username(username):
        """通过用户名查找用户"""
        print(f"Looking for user: {username}")  # 调试信息
        print(f"Current users: {[u.username for u in db.users]}")  # 调试信息
        for user in db.users:
            if user.username == username:
                return user
        return None
    
    @staticmethod
    def find_by_id(user_id):
        """通过ID查找用户"""
        for user in db.users:
            if user.id == int(user_id):
                return user
        return None
    
    def __repr__(self):
        return f'<User {self.username}>'
    
    def update(self, data):
        """更新用户信息"""
        try:
            self.username = data.get('username', self.username)
            self.email = data.get('email', self.email)
            self.role = data.get('role', self.role)
            self.is_active = data.get('is_active', self.is_active)
            
            if 'password' in data and data['password']:
                self.set_password(data['password'])
            
            return True
        except Exception as e:
            print(f"Error updating user: {str(e)}")
            return False
    
    def delete(self):
        """删除用户"""
        try:
            db.users.remove(self)
            return True
        except Exception as e:
            print(f"Error deleting user: {str(e)}")
            return False
            
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'username': self.username,
            'email': self.email,
            'role': self.role,
            'is_active': self.is_active,
            'created_at': self.created_at.isoformat()
        } 